/*******************************************************************************
 * Copyright (c) 2011 LegSem.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v3.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/gpl-3.0.txt
 * 
 * Contributors:
 *     LegSem - initial API and implementation
 ******************************************************************************/
package com.legstar.eci.xmi;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.legstar.eci.xmi.model.WsdlDefinitions;
import com.thoughtworks.xstream.XStream;

/**
 * Reads ECI XMI binding wsdl and builds a model of java objects. The WSDL is
 * expected to contain ECI specific bindings implemented as XMI (XML Metadata
 * Interchange).
 * 
 */
public class EciXmiReader {

    /** Logging. */
    private Log _log = LogFactory.getLog(getClass());

    /** An XStream processor. */
    private XStream _xstream;

    public EciXmiReader() {
        AttrStaxDriver driver = new AttrStaxDriver(
                EciXmiConfig.getQNameMap(), EciXmiConfig.getAttrNSMap());
        _xstream = new XStream(driver);
        _xstream.processAnnotations(WsdlDefinitions.class);
    }

    /**
     * Read a file containing ECI XMI wsdl and builds a model.
     * 
     * @param wsdlFile the ECI wsdl file
     * @return java model holding ECI meta data
     */
    public WsdlDefinitions read(final File wsdlFile) throws IOException {
        return read(wsdlFile, null);
    }

    /**
     * Read a file containing ECI XMI wsdl and builds a model.
     * 
     * @param wsdlFile the ECI wsdl file
     * @param encoding the ECI wsdl file encoding
     * @return java model holding ECI meta data
     */
    public WsdlDefinitions read(final File wsdlFile,
            final String encoding) throws IOException {

        if (_log.isDebugEnabled()) {
            _log.debug("Reading file " + wsdlFile.getAbsolutePath());
        }

        Reader reader = null;
        if (encoding == null || encoding.length() == 0) {
            reader = new InputStreamReader(
                    new FileInputStream(wsdlFile));
        } else {
            reader = new InputStreamReader(
                    new FileInputStream(wsdlFile), encoding);
        }

        WsdlDefinitions result =
                (WsdlDefinitions) _xstream.fromXML(reader);

        if (_log.isDebugEnabled()) {
            _log.debug(result.toString());
        }

        return result;

    }

}
